let Sequelize = require('sequelize');
let db = require('../libs/db.lib');
let config = require('../config');

let Setting = db.define('setting', {
    // 设置项key值
    key: {
        type: Sequelize.STRING(20),
        primaryKey: true,
        unique: true,
        allowNull: false,
    },
    // 设置项名称
    name: {
        type: Sequelize.STRING(100),
        allowNull: false,
    },
    // 设置的存储类型，0 string 1 int 2 bool 3 array 4 json
    type: {
        type: Sequelize.TINYINT,
        allowNull: false,
        defaultValue: 0,
        comment: '设置的存储类型，0 string 1 int 2 bool 3 array 4 json',
    },
    // 这里多个存储字段 主要是为了方便切换 存储类型
    // string值
    string: Sequelize.TEXT,
    // int值
    int: Sequelize.INTEGER,
    // bool值
    bool: Sequelize.BOOLEAN,
    // array值
    array: {
        type: Sequelize.TEXT,
        get() {
            try {
                return JSON.parse(this.getDataValue('array'));
            } catch (e) {
                return [];
            }

        },
        set(val) {
            this.setDataValue('array', JSON.stringify(val));
        },
    },
    // json值
    json: {
        type: Sequelize.TEXT,
        get() {
            try {
                return JSON.parse(this.getDataValue('json'));
            } catch (e) {
                return {};
            }
        },
        set(val) {
            this.setDataValue('json', JSON.stringify(val));
        },
    },
    // builtIn 内置值，不能删除
    builtIn: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: 0,
    },
}, {
    timestamps: false,
});

Setting.prototype.value = function () {
    switch (this.type) {
        case 0:
            return this.string;
        case 1:
            return this.int;
        case 2:
            return this.bool;
        case 3:
            return this.array;
        case 4:
            return this.json;
        default:
            return null;

    }
};

// 同步model到table 插入默认数据记录
Setting.sync({alter: true}).then(async () => {
    let builtInDatas = [{
        key: 'appName',
        name: '站点名称',
        builtIn: true,
        type: 0,
        string: 'CatVod',
    }, {
        key: 'appOpenReg',
        name: '开放注册',
        builtIn: true,
        type: 2,
        bool: false,
    }, {
        key: 'autoCJ',
        name: '开启自动采集(每30分钟采集（当天）一次)',
        builtIn: true,
        type: 2,
        bool: false,
    }, {
        key: 'vipFlags',
        name: 'VIP解析站点',
        builtIn: true,
        type: 3,
        array: [
            'youku',
            'qq',
            'iqiyi',
            'qiyi',
            'letv',
            'sohu',
            'tudou',
            'pptv',
            'mgtv',
            'wasu',
        ],
    }, {
        key: 'pic2tu',
        name: '采集图片地址处理',
        builtIn: true,
        type: 4,
        json: {
            'pic': 'http://api.zz22x.com/iiimg.php?pic=',
            'fixs': [
                'img.php?pic=',
                'img.php?img=',
                'tu.php?tu=',
            ],
            'hosts': [
                'iqiyipic.com',
                'qiyipic.com',
                'qiyipic1.com',
                'doubanio.com',
                'hiphotos.baidu.com',
                'photocdn.tv.sohu.com',
            ],
        },
    }, {
        key: 'vipParser',
        name: 'VIP解析地址',
        builtIn: true,
        type: 0,
        string: 'https://jiexi.bm6ig.cn/?url=',
    }, {
        key: 'srcPlayers',
        name: '播放器配置',
        builtIn: true,
        type: 4,
        json: {
            "hkm3u8": "http://play.jiningwanjun.com/dpm3u8.html?v=",
            "Q4": "http://j.wfss100.com/?url=",
            "Q6": "http://j.wfss100.com/?url=",
            "Q8": "http://j.wfss100.com/?url=",
        },
    }];
    for (let index in builtInDatas) {
        let data = builtInDatas[index];
        await Setting.findOne({attributes: ['key'], where: {key: data.key}}).then((s) => {
            if (!s) {
                return Setting.create(data).then(s => {
                    if (s) {
                        console.log(`配置${s.name}添加成功！`);
                    }
                }).catch(e => {
                    console.log(e);
                });
            }
        });
    }
    // setting 同步到 config
    await Setting.findAll().then(ss => {
        for (let idx in ss) {
            let row = ss[idx];
            config.system[row.key] = row.value();
        }
    }).catch(e => {
        console.log(e);
    });
});

module.exports = Setting;
